package com.njit.campuslifeboot.aop;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njit.campuslifeboot.entity.po.User;
import com.njit.campuslifeboot.service.IUserService;
import com.njit.campuslifeboot.util.JsonResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthorityAspect {
    @Autowired
    private IUserService userService;

    @Pointcut(value = "@annotation(com.njit.campuslifeboot.annotation.AuthAnnotation)")
    public void checkAuthority() {
    }

    @Around("checkAuthority()")
    public JsonResult<String> checkAuth(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取到请求的属性
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取到请求对象
        HttpServletRequest request = attributes.getRequest();
        String username = request.getHeader("auth");
        User user = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        if (user == null) {
            return JsonResult.authFail(username + " is not exist");
        } else {
            joinPoint.proceed();
            return JsonResult.success();
        }
    }
}
